import "package:share_image_server/export_all.dart";


//
// auth: Du Long
// date: 2024-09-15
// description:
//

String? mimeTypeFromPath(String path) {
  // 根据文件路径返回MIME类型
  // 这里是一个简单的例子，可以根据文件扩展名返回MIME类型
  final extension = path.split('.').last;
  if (allowedContentType.containsKey(extension)) {
    return allowedContentType[extension];
  }
  return null;
}

Future<Response> imagesService(Request request) async {
  final image = request.params['uuid'];
  ResponseApi responseApi = ResponseApi(code: 200, msg: "成功", dataType: "String", data: "");

  // 定义静态文件目录
  final staticFilesDirectory = Directory(imagePath);

  // 检查静态文件目录是否存在
  if (!await staticFilesDirectory.exists()) {
    responseApi.code = 404;
    responseApi.msg = "非法访问，你已被记录，请等待审核...";
    logE(staticFilesDirectory.toString());
    responseApi.data = image.toString();
    return Response(responseApi.code, body: responseApiToJson(responseApi))
      .change(headers: {"content-type": "application/json"});
  }

  // 尝试获取文件路径
  final filePath = "${staticFilesDirectory.path}/$image";
  final file = File(filePath);

  // 检查文件是否存在
  if (!await file.exists()) {
    responseApi.code = 404;
    responseApi.msg = "文件丢失或文件不存在";
    return Response(responseApi.code, body: responseApiToJson(responseApi))
      .change(headers: {"content-type": "application/json"});
  }

  // 读取文件内容
  final content = await file.readAsBytes();
  String? fileType = mimeTypeFromPath(filePath);
  if (fileType == null) {
    responseApi.code = 403;
    responseApi.msg = "非法访问，该文件不支持获取,你已被记录，请等待审核...";
    return Response(responseApi.code, body: responseApiToJson(responseApi))
      .change(headers: {"content-type": "application/json"});
  }

  return Response.ok(content).change(headers: {"Content-Type": fileType});
}
